package net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import message.Packet;

class Receiver implements Runnable {
	private ServerSocket clientInputSocket = null;
	
	Receiver() {
		this.clientInputSocket = this.setUpServerSocket(OlivawPortsClient.getInputPort());
	}
	
	private ServerSocket setUpServerSocket(int inputPort){
		ServerSocket ss = null;
		while(true){
			try {
				ss = new ServerSocket(inputPort);
				OlivawPortsClient.setInputPort(inputPort);
				return ss;
			} catch (IOException e) {
				inputPort++;
			}
		}
	}

	@Override
	public void run() {
		while (true) {
			try {
				this._run();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void _run() throws IOException {
		Socket clientSocket = clientInputSocket.accept();

		PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
		BufferedReader in = new BufferedReader(new InputStreamReader(
				clientSocket.getInputStream()));

		String packetRappresentation = in.readLine();

		System.out.println(packetRappresentation);

		out.write(Packet.OK);
		
		out.close();
		in.close();
		clientSocket.close();
	}

	@Override
	protected void finalize() throws Throwable {
		clientInputSocket.close();
	}
}
